package com.bicon.bdata_service_search.es.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bicon.bdata_service_search.es.bean.AnswerDetailBean;
import com.bicon.bdata_service_search.es.bean.AskAnswerBean;
import com.bicon.bdata_service_search.es.bean.ResultAnswerDetailBean;
import com.bicon.bdata_service_search.es.bean.ResultAskAnswerListBean;
import com.bicon.bdata_service_search.es.common.result.Result;
import com.bicon.bdata_service_search.es.common.result.ResultEnum;
import com.bicon.bdata_service_search.es.common.result.ResultUtil;
import com.bicon.bdata_service_search.es.entities.QuestionAndAnswer;
import com.bicon.bdata_service_search.es.service.ESQuestionAndAnswerService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 *
 * @author zhaoyu
 * @email zhaoyu@vv.cc
 * @create 2018-09-07 16:14
 */
@RestController
public class ESFindController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ESQuestionAndAnswerService esQuestionAndAnswerServiceImpl;

    @Autowired
    Client client;

    @RequestMapping(value = "/ESFind1", method = RequestMethod.GET)
    public Page<QuestionAndAnswer> ESFind1(@RequestParam(value = "askContent", defaultValue = "孟大夫") String askContent, @RequestParam(value = "page", defaultValue = "0") Integer page,
                                           @RequestParam(value = "size", defaultValue = "15") Integer size) {
        Pageable pageable = new PageRequest(page, size);
        return esQuestionAndAnswerServiceImpl.esFind1(askContent, pageable);
    }

    @RequestMapping(value = "/ESSearch", method = RequestMethod.GET)
    public Page<QuestionAndAnswer> ESSearch(@RequestParam(value = "askContent", defaultValue = "孟大夫") String askContent, @RequestParam(value = "page", defaultValue = "0") Integer page,
                                            @RequestParam(value = "size", defaultValue = "15") Integer size) {
        Pageable pageable = new PageRequest(page, size);
        return esQuestionAndAnswerServiceImpl.search(askContent, pageable);
    }
    @ApiOperation(value="获取问答搜索列表信息", notes="根据输入内容模糊查询相关的问答信息")
    @ApiImplicitParam(name = "askContent", value = "需要搜索的问题相关信息", required = true, dataType = "String")
    @RequestMapping(value = "/getAskAnswerList2", method = RequestMethod.GET)
    public Result ESClientSearch(@RequestParam(value = "askContent", defaultValue = "孟大夫") String askContent, @RequestParam(value = "page", defaultValue = "0") Integer page,
                                 @RequestParam(value = "size", defaultValue = "15") Integer size) {
//        QueryBuilder qb1 = QueryBuilders.queryStringQuery("发烧了头痛");
        SearchResponse response = client.prepareSearch("question_and_answer_realtime_index").setQuery(QueryBuilders.matchQuery("askContent", askContent)).setTypes("questionAndAnswerRealtime").setPreference("_primary").setFrom(page).setSize(size).get();
        // 查询的总数(命中数)
        SearchHits hits = response.getHits();
        long totalHits = hits.getTotalHits();
        // 遍历查询的结果
        ResultAskAnswerListBean resultAskAnswerListBean = new ResultAskAnswerListBean();
        ArrayList<AskAnswerBean> askAnswerBeans = new ArrayList<>();
//        resultAskAnswerListBean
        for (SearchHit next : hits) {
            // System.out.println(next.getSourceAsString());
            String id = next.getId();
            Map<String, Object> source = next.getSource();
            AskAnswerBean askAnswerBean = new AskAnswerBean();
            askAnswerBean.setAskEsId(id);
            askAnswerBean.setAskContent((String) source.get("askContent"));
            String a = (String) source.get("answers");
            int answer_num = JSON.parseArray(a).size();
            askAnswerBean.setAnswerNum(answer_num);
            askAnswerBean.setDoctorImg(getDoctorImgFromAnswer((String) source.get("answers")));
            askAnswerBeans.add(askAnswerBean);
//            System.out.println(productId);
//            System.out.println(productId);
        }
        resultAskAnswerListBean.setRecords(askAnswerBeans);
        resultAskAnswerListBean.setCurrent(page);
        resultAskAnswerListBean.setSize(size);
        resultAskAnswerListBean.setTotal((int) totalHits);
        return ResultUtil.success(resultAskAnswerListBean);

    }
    @ApiOperation(value="获取问答详情", notes="根据id查询对应的问答详情")
    @ApiImplicitParam(name = "askEsId", value = "问答信息的askEsId", required = true, dataType = "String")
    @RequestMapping(value = "/getAskAnswerDetail", method = RequestMethod.GET)
    public Result searchDetailById(String askEsId) {
        GetResponse response = client.prepareGet("question_and_answer_realtime_index", "questionAndAnswerRealtime", askEsId)
                .setOperationThreaded(false)    // 线程安全
                .get();
//        System.out.println(response.getSourceAsMap());
//        JSONObject detail = JSON.parseObject(response.getSourceAsString());
        Map<String, Object> detail = response.getSourceAsMap();
        if(null ==detail){
            return ResultUtil.error(10001001,"param error or not in es");
        }
        String askContent = (String) detail.get("askContent");
//    String answer = questionAndAnswer_md5.getAnswers();
//
        ResultAnswerDetailBean resultAnswerDetailBean = new ResultAnswerDetailBean();
        ArrayList<AnswerDetailBean>  answerDetailBeans =getAnswerDetail((String) detail.get("answers"));
//    resultAnswerDetailBean.setSize(1);
//    resultAnswerDetailBean.setPage(0);
    resultAnswerDetailBean.setAskTime((String) detail.get("askSex"));
    resultAnswerDetailBean.setAskSex((String) detail.get("askSex"));
    resultAnswerDetailBean.setAskAge((String) detail.get("askAge"));
    resultAnswerDetailBean.setSourceWeb((String) detail.get("sourceWeb"));
    resultAnswerDetailBean.setAskEsId(askEsId);
    resultAnswerDetailBean.setAskContent(askContent);
    resultAnswerDetailBean.setAskDepartment((String) detail.get("askDepartment"));
    resultAnswerDetailBean.setAskNum(answerDetailBeans.size());
    resultAnswerDetailBean.setRecords(answerDetailBeans);

        return ResultUtil.resultWithData(ResultEnum.SUCCESS,resultAnswerDetailBean);
    }

    private String[] getDoctorImgFromAnswer(String answer) {
        JSONArray answer_json = JSON.parseArray(answer);
        int json_lenth = answer_json.size();
        List<String> rst = new ArrayList<>();
        for (int i = 0; i < json_lenth; i++) {
            JSONObject answer_temp = answer_json.getJSONObject(i);
            String img_str = (String) answer_temp.get("doctor_img");
            if (StringUtils.isEmpty(img_str)) {
                continue;
            }
            rst.add(img_str);
        }
        return rst.toArray(new String[rst.size()]);
    }

    private ArrayList<AnswerDetailBean> getAnswerDetail (String answer){
        JSONArray answer_json = JSON.parseArray(answer);
        int json_lenth = answer_json.size();
        List<String> rst = new ArrayList<>();
        ArrayList<AnswerDetailBean> answerDetailBeans = new ArrayList<>();

        for (int i = 0; i < json_lenth; i++) {
            AnswerDetailBean answerDetailBean = new AnswerDetailBean();
            JSONObject answer_temp = answer_json.getJSONObject(i);
//            String img_str = (String) answer_temp.get("doctor_img");
            answerDetailBean.setDoctor_name((String) answer_temp.get("doctor_name"));
            answerDetailBean.setDoctor_pos((String) answer_temp.get("doctor_pos"));
            answerDetailBean.setDoctor_hos((String) answer_temp.get("doctor_hos"));
            answerDetailBean.setDoctor_good((String)answer_temp.get("doctor_good"));
            answerDetailBean.setDoctor_dep((String)answer_temp.get("doctor_dep"));
            answerDetailBean.setDoctor_img((String) answer_temp.get("doctor_img"));
            answerDetailBean.setAnswer_time((String) answer_temp.get("answer_time"));
            answerDetailBean.setAnswer_content((String) answer_temp.get("answer_content"));
            answerDetailBeans.add(answerDetailBean);
        }
        return answerDetailBeans;
    }
}